import { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout'
import ParentView from '@/components/ParentView'
import { adaptRoutesResponse } from '@/utils/adapter'

// 组件映射关系
const componentMap = {
    Layout: Layout,
    ParentView: ParentView
}

/**
 * 使用递归过滤异步路由表
 * @param routes 异步路由表
 * @param permissions 用户权限
 */
function filterAsyncRoutes(routes, permissions) {
    console.log('过滤路由:', { routesCount: routes.length, permissions })
    const res = []

    // 图标映射表 - 将后端返回的图标名称映射到Element UI图标类名
    const iconMap = {
        'settings': 'el-icon-setting',
        'user': 'el-icon-user',
        'role': 'el-icon-s-check',
        'configuration': 'el-icon-s-tools',
        'params': 'el-icon-s-operation',
        'dashboard': 'el-icon-s-home',
        'dict': 'el-icon-notebook-1',
        'dept': 'el-icon-office-building',
        'menu': 'el-icon-menu',
        'product': 'el-icon-goods',
        'category': 'el-icon-collection',
        'order': 'el-icon-s-order',
        'statistics': 'el-icon-data-line'
    }

    routes.forEach(route => {
        const tmp = { ...route }

        if (hasPermission(permissions, tmp)) {
            // 处理meta数据
            if (tmp.meta) {
                // 处理图标，使用映射表
                if (tmp.meta.icon) {
                    tmp.meta.icon = iconMap[tmp.meta.icon] || 'el-icon-' + tmp.meta.icon
                }

                // 将meta中的alwaysShow提升到路由对象的顶层
                if (tmp.meta.alwaysShow !== undefined) {
                    tmp.alwaysShow = tmp.meta.alwaysShow === true || tmp.meta.alwaysShow === 'true'
                }

                // 将meta中的hidden提升到路由对象的顶层
                if (tmp.meta.hidden !== undefined) {
                    tmp.hidden = tmp.meta.hidden === true || tmp.meta.hidden === 'true'
                }
            }

            // 处理组件
            if (tmp.component) {
                // 先检查组件映射
                if (componentMap[tmp.component]) {
                    tmp.component = componentMap[tmp.component]
                } else if (tmp.component === 'Layout') {
                    tmp.component = Layout
                } else if (tmp.component === 'ParentView') {
                    tmp.component = ParentView
                } else {
                    // 动态加载组件
                    try {
                        console.log(`加载组件: ${tmp.component}，路径: ${tmp.path}`)
                        tmp.component = loadView(tmp.component)
                    } catch (error) {
                        console.error('加载组件失败:', tmp.component, error)
                        // 如果加载失败，使用空组件
                        tmp.component = ParentView
                    }
                }
            } else {
                // 如果没有组件但有子路由，使用ParentView
                if (tmp.children && tmp.children.length > 0) {
                    console.log(`为路由 ${tmp.path} 设置默认组件 ParentView`)
                    tmp.component = ParentView
                }
            }

            // 递归处理子路由
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, permissions)
            }

            res.push(tmp)
        }
    })

    return res
}

/**
 * 判断用户是否拥有权限
 * @param permissions 用户权限
 * @param route 路由
 */
function hasPermission(permissions, route) {
    // 如果用户具有admin角色或*:*:*权限，则拥有所有权限
    if (permissions.includes('*:*:*')) {
        return true
    }

    if (route.meta && route.meta.permission) {
        return permissions.some(permission => permission === route.meta.permission)
    } else {
        return true
    }
}

/**
 * 动态加载组件
 * @param view 组件路径
 */
export const loadView = (view) => {
    // 打印加载的组件路径
    console.log('加载组件:', view)

    // 处理组件路径，确保格式正确
    const componentPath = view.replace(/^\/+/, '')
    console.log('处理后的组件路径:', componentPath)

    if (process.env.NODE_ENV === 'development') {
        return (resolve) => {
            try {
                require([`@/views/${componentPath}`], resolve)
            } catch (e) {
                console.error('组件加载失败:', e)
                resolve(ParentView)
            }
        }
    } else {
        // 生产环境使用懒加载
        return () => {
            try {
                return import(`@/views/${componentPath}`)
            } catch (e) {
                console.error('组件加载失败:', e)
                return Promise.resolve(ParentView)
            }
        }
    }
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    // 生成动态路由
    generateRoutes({ commit }, { roles, permissions }) {
        console.log('生成动态路由:', { roles, permissions })
        return new Promise(resolve => {
            // 默认管理员拥有所有权限
            const isAdmin = roles.includes('admin')

            // 如果是管理员，添加全部权限
            let userPermissions = permissions
            if (isAdmin && !permissions.includes('*:*:*')) {
                userPermissions = ['*:*:*', ...permissions]
            }

            getRouters().then(res => {
                console.log('获取路由响应:', res)

                // 使用适配器处理响应
                const routesData = adaptRoutesResponse(res)
                console.log('适配后的路由数据:', routesData)

                const asyncRoutes = filterAsyncRoutes(routesData, userPermissions)
                console.log('过滤后的路由:', asyncRoutes)

                commit('SET_ROUTES', asyncRoutes)
                resolve(asyncRoutes)
            }).catch(error => {
                console.error('获取路由失败:', error)
                // 即使失败也返回空路由，避免页面阻塞
                commit('SET_ROUTES', [])
                resolve([])
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
} 